<?php

namespace app\admin\controller\vip;

use app\common\controller\Backend;
use think\Db;
use think\Config;
use think\Validate;
use think\captcha\Captcha;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use think\exception\PDOException;
use think\Exception;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Excels extends Backend
{
    
    /**
     * Excels模型对象
     * @var \app\admin\model\vip\Excels
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\vip\Excels;
        $this->view->assign("statusList", $this->model->getStatusList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 添加
     */
    public function add()
    {
        ini_set("memory_limit","800M");
        set_time_limit(0);
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $params['id'] = $this->model->id;
                    $re = $this->save_orders($params);
                    if($re['status'] == 200){
                        $this->success();
                    } else {
                        $this->error($re['msg']);
                    }
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }


    /**
     * 保存流水记录
     */
    public function save_orders($excel)
    {
        $time = time();
        $savetime = strtotime($excel["addtime"]);
        $file = $excel["file"];

        if (!$file) {
            $this->edit_excels($excel["id"],4,__('Parameter %s can not be empty', 'file'));
            return ["status"=>401,"msg"=>__('Parameter %s can not be empty', 'file')];
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->edit_excels($excel["id"],4,__('No results were found'));
            return ["status"=>401,"msg"=>__('No results were found')];
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->edit_excels($excel["id"],4,__('Unknown data format'));
            return ["status"=>401,"msg"=>__('Unknown data format')];
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, "w");
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding != 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = (new \app\admin\model\vip\Orders)->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->edit_excels($excel["id"],4,__('Unknown data format'));
                return ["status"=>401,"msg"=>__('Unknown data format')];
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }

            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                $row = [];
                $temp = array_combine($fields, $values);
                foreach ($temp as $k => $v) {
                    if (isset($fieldArr[$k]) && $k !== '') {
                        $row[$fieldArr[$k]] = $v;
                    }
                }


                if ($row) {
                    // 处理每一个用户数据
                    $row['username'] = trim($row['username']);
                    $row["status"] = 0;
                    $row["savetime"] = $savetime;
                    $row["createtime"] = $time;

                    $insert[] = $row;

                    // 分批导入
                    if(count($insert) >= 2000){
                        Db::name("vip_orders")->insertAll($insert);
                        unset($insert);
                        $insert = [];
                    }

                }
            }
            try{
                if(empty($insert)){
                    $this->edit_excels($excel["id"],1,"操作成功");
                    return ["status"=>200,"msg"=>"操作成功"];
                }
                Db::name("vip_orders")->insertAll($insert);
                $this->edit_excels($excel["id"],1,"操作成功");
                return ["status"=>200,"msg"=>"操作成功"];
            } catch (PDOException $exception) {
                $this->edit_excels($excel["id"],4,$exception->getMessage());
                return ["status"=>401,"msg"=>$exception->getMessage()];
            } catch (\Exception $e) {
                $this->edit_excels($excel["id"],4,$e->getMessage());
                return ["status"=>401,"msg"=>$e->getMessage()];
            }

        } catch (Exception $exception) {
            $this->edit_excels($excel["id"],4,$exception->getMessage());
            return ["status"=>401,"msg"=>$exception->getMessage()];
        }
    }
    /**
     * 修改Excel状态
     */
    public function edit_excels($id,$status,$msg)
    {
        //$redis->unlock($key);
        Db::name("vip_excels")->where("id",$id)->update(["status"=>$status,"createtime"=>time(),"msg"=>$msg]);
    }


    /**
     * 回滚数据
     */
    public function rollback()
    {
        if($this->request->isPost()){
            //$oldtime = Db::name("vip_orders")->where("status",1)->order("savetime desc")->value("savetime");
            //dump(strtotime(input("backtime")));
            //dump($oldtime);
            //if(strtotime(input("backtime")) != $oldtime){
            //    echo 111;
            //    $this->error("请先回滚".date("Y-m-d",$oldtime)."数据");
            //}
            //die;
            if(!captcha_check(input("captcha"))){
                $this->error("验证码错误");
            };

            $backtime = input("backtime");
            if(empty($backtime)){
                $this->error("回滚时间不能为空");
            }
            $backtime = strtotime($backtime);
            $count = Db::name("vip_orders")->where("status",0)->where("savetime",$backtime)->count();
            if($count > 0){
                $this->error("请等待数据合并完后在回滚当前时间的数据");
            }
            // 查询回滚的时间是否最新
            $oldtime = Db::name("vip_orders")->where("status",1)->order("savetime desc")->value("savetime");
            if($backtime != $oldtime){
                $this->error("请先回滚".date("Y-m-d",$oldtime)."数据");
            }
            $re = Db::name("vip_orders")->where("savetime",$backtime)->where("status",1)->update(["status"=>2]);
            if($re !== false){
                Db::name("vip_haoyun")->where("savetime",date("Y-m",strtotime($backtime)))->delete();
                $this->success("回滚成功，系统稍后将自动删除对应的奖金");
            } else {
                $this->error("回滚失败");
            }
        }
        return $this->view->fetch();
    }

    public function captcha()
    {
        $config = [
            'fontSize' => 35,
            'fontttf' => '5.ttf',
            'codeSet' => '1234567890',
            'length' => 4,
            'useNoise' => false,
            'useCurve' => false
        ];
        $captcha = new Captcha($config);
        return $captcha->entry();
    }
    

    public function down_haoyun()
    {
        $down_time = input("down_time");
        if(empty($down_time)){
            $this->error("导出时间不能为空");
        }
        $re = Db::name("vip_haoyun")->alias("a")->field("a.*,b.level")->join("vip_user b","a.username = b.username")->where("a.savetime",$down_time)->select();
        $data = [];
        foreach ($re as $k => $v) {
            $data[] = [
                $v['username'],$v['money'],$v['money'],"Y","VIP {$v['level']}好运金"
            ];
        }

        $title = [
            [
                '会员账号', '存款金额','综合打码稽核','写入退佣费用(Y/N)','备注'
            ],
        ];
        $arrData = array_merge($title, $data);
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();

        // 设置单元格格式 可以省略
        $styleArray = [
            'font' => [
                'bold' => true,
                'size' => 14,
            ],
            'text-align' => 'center',
        ];
        $spreadsheet->getActiveSheet()->getStyle('A2:A3')->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
        //$spreadsheet->getActiveSheet()->getStyle('A1:B1')->applyFromArray($styleArray);
        //$spreadsheet->getActiveSheet()->getColumnDimension('A')->setWidth(25);
        //$spreadsheet->getActiveSheet()->getColumnDimension('B')->setWidth(25);
        $spreadsheet->getActiveSheet()->fromArray($arrData);
        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');//告诉浏览器输出07Excel文件
        // header('Content-Type:application/vnd.ms-excel');//告诉浏览器将要输出Excel03版本文件
        header("Content-Disposition: attachment;filename=[{$down_time}]用户好运金.csv");//告诉浏览器输出浏览器名称
        header('Cache-Control: max-age=0');//禁止缓存
        $writer->save('php://output');
        exit;
    }
    public function down_jinji()
    {
        $down_time = input("down_time");
        if(empty($down_time)){
            $this->error("导出时间不能为空");
        }
        $re = Db::name("vip_jiangli")->where("month",$down_time)->select();
        $data = [];

        $jiangli_data = Db::name("vip_description")->cache(true)->select();
        $jiangli_data = array_column($jiangli_data,"money","level");


        foreach ($re as $k => $v) {
            $oldleve = _uplevel($v['level'],$v['money'],$jiangli_data);
            $data[] = [
                $v['username'],$v['money'],$v['money'],"Y","VIP {$oldleve} --> VIP {$v['level']}晋级奖励"
            ];


            //$oldLevel = $v['level'] - 1;
            //$data[] = [
            //    $v['username'],$v['money'],$v['money'],"Y","VIP {$oldLevel} --> VIP {$v['level']}晋级奖励"
            //];
        }
        $title = [
            [
                '会员账号', '存款金额','综合打码稽核','写入退佣费用(Y/N)','备注'
            ],
        ];
        $arrData = array_merge($title, $data);
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $spreadsheet->getActiveSheet()->fromArray($arrData);
        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');//告诉浏览器输出07Excel文件
        header("Content-Disposition: attachment;filename=[{$down_time}]用户晋级奖励.csv");//告诉浏览器输出浏览器名称
        header('Cache-Control: max-age=0');//禁止缓存
        $writer->save('php://output');
        exit;
    }
    public function down_chouma()
    {
        $down_time = input("down_time");
        if(empty($down_time)){
            $this->error("导出时间不能为空");
        }
        $re = Db::name("vip_chouma")->alias("a")->field("a.*,b.level")->join("vip_user b","a.username = b.username")->where("a.month",$down_time)->select();
        //dump(Db::name("vip_chouma")->getLastSql());
        //dump($re);die;
        $data = [];
        foreach ($re as $k => $v) {
            $data[] = [
                $v['username'],$v['money'],$v['money'],"Y","VIP {$v['level']}月月免费筹码"
            ];
        }
        $title = [
            [
                '会员账号', '存款金额','综合打码稽核','写入退佣费用(Y/N)','备注'
            ],
        ];
        $arrData = array_merge($title, $data);
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $spreadsheet->getActiveSheet()->fromArray($arrData);
        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');//告诉浏览器输出07Excel文件
        header("Content-Disposition: attachment;filename=[{$down_time}]月月免费筹码.csv");//告诉浏览器输出浏览器名称
        header('Cache-Control: max-age=0');//禁止缓存
        $writer->save('php://output');
        exit;
    }
}
